﻿using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
class AutoSizeFormClass
{
    public struct controlScale //每个控件相对于父控件的缩放比例
    {
        public float xScale;//坐标x
        public float yScale;//坐标y
        public float wScale;//控件宽
        public float hScale;//控件高
        public float fScale;//字体
    }
   
    public List<controlScale> scaleList = new List<controlScale>();

    private int ctrlNo = 0;

    public void controllInitializeSize(Control mForm)
    {
        scaleList.Clear();

        AddControl(mForm,(float)mForm.ClientSize.Width,(float)mForm.ClientSize.Height);        
    }
    private void AddControl(Control ctl,float w,float h)
    {
        foreach (Control c in ctl.Controls)
        {
            controlScale cR;

            cR.xScale = c.Left / w;

            cR.yScale = c.Top / h;

            cR.wScale = c.Width / w;

            cR.hScale = c.Height / h;

            cR.fScale = c.Font.Size/h;

            scaleList.Add(cR);
            if (c.Controls.Count > 0)
                AddControl(c,(float)c.Width,(float)c.Height);//递归
        }
    }

    public void controlAutoSize(Control mForm)
    {
        if (scaleList.Count < 1 || mForm.Width < 1)
        {
            return;
        }
        ctrlNo = 0;

        AutoSize(mForm, (float)mForm.ClientSize.Width, (float)mForm.ClientSize.Height);
    }
    private void AutoSize(Control ctl, float w, float h)
    {
        foreach (Control c in ctl.Controls) 
        {
            c.Left = (int)(scaleList[ctrlNo].xScale * w);

            c.Top = (int)(scaleList[ctrlNo].yScale * h);

            c.Width = (int)(scaleList[ctrlNo].wScale * w);

            c.Height = (int)(scaleList[ctrlNo].hScale * h);

            Font nFont=new Font(c.Font.Name, (int)(scaleList[ctrlNo].fScale * h), c.Font.Style);

            c.Font = nFont;
          
            ctrlNo++;

            if (c.Controls.Count > 0)
                AutoSize(c, c.Width, c.Height);//递归
        }
    }
}
